class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int diff = INT_MAX;
        int res;
        for (int i = 0; i < nums.size() - 2; i++)
        {
            int j = i + 1;
            int k = nums.size() - 1;
            do
            {
                int temp = nums[i] + nums[j] + nums[k];
                if(temp == target) return temp;
                if(abs(temp - target) < diff)
                {
                    diff = abs(temp - target);
                    res = temp;
                }
                if(temp - target > 0) k--;
                else j++;
            } while(j != k);
        }
        return res;
    }
};
